package org.benjamin.lending.service.impl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.benjamin.lending.domain.entity.ConfigurationParameter;
import org.benjamin.lending.repository.ConfigurationParameterRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class InitializeInterceptor extends HandlerInterceptorAdapter {
	
	@Autowired
	private ConfigurationParameterRepository configurationParameterRepository;
	
	private ConfigurationParameter configurationParameter;

	public ConfigurationParameter initialSystemConfig() {
		ConfigurationParameter configurationParameter = this.configurationParameterRepository.findOne("001");
		if(configurationParameter == null) {
			configurationParameter = new ConfigurationParameter();
			configurationParameter.setServiceTime("9:00-21:00");
			configurationParameter.setServicePhone("400-1212-1212");
			return configurationParameter;
		}
		if(StringUtils.isBlank(configurationParameter.getServicePhone())) {
			configurationParameter.setServicePhone("400-1212-1212");
		}
		if(StringUtils.isBlank(configurationParameter.getServiceTime())) {
			configurationParameter.setServiceTime("9:00-21:00");
		}
		return configurationParameter;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		Object object = request.getServletContext().getAttribute("configurationParameter");
		if(object == null) {
			if(this.configurationParameter == null) {
				this.configurationParameter = this.initialSystemConfig();
			}
			
			request.getServletContext().setAttribute("configurationParameter", this.configurationParameter);
		}
		
		return true;
	}
	
	
}
